﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Protocol;
using System.Diagnostics.Contracts;
using System.IO;
namespace MDS
{
    public class EtfListParser_ETF : IEtfListParser
    {


        public GWMKTETFListANS Parse(string etfListFileContent, StockExchange exch)
        {
            Contract.Requires(!string.IsNullOrEmpty(etfListFileContent));
            GWMKTETFListANS rtn = new GWMKTETFListANS();
            rtn.FundMarketID = exch.ToString();
            Dictionary<string, string> keyValue = new Dictionary<string, string>();
            var matches = Regex.Matches(etfListFileContent, @"^([^\r\n]*?)=([^\r\n]*?)$");
            foreach (Match m in matches)
            {
                keyValue[m.Groups[1].Value] = m.Groups[2].Value;
            }
            if (keyValue.ContainsKey("Fundid1"))
            {
                rtn.FundID = rtn.FundMarketID + keyValue["Fundid1"];
            }
            else if (keyValue.ContainsKey("FundID"))
            {
                rtn.FundID = rtn.FundMarketID + keyValue["FundID"];
            }
            if (keyValue.ContainsKey("FundName"))
            {
                rtn.FundName = keyValue["FundName"];
            }
            if (keyValue.ContainsKey("CreationRedemptionUnit"))
            {
                rtn.CreationRedemptionUnit = tryParseInt32(keyValue["CreationRedemptionUnit"]);
            }
            if (keyValue.ContainsKey("EstimateCashComponent"))
            {
                rtn.ETFEstimateSettlementCashAmt = tryParseDouble(keyValue["EstimateCashComponent"]);
            }
            if (keyValue.ContainsKey("MaxCashRatio"))
            {
                rtn.MaxCashRatio = tryParseDouble(keyValue["MaxCashRatio"]);
            }
            if (keyValue.ContainsKey("Creation"))
            {
                rtn.CreationFlag = tryParseInt32(keyValue["Creation"]);
            }
            else if (keyValue.ContainsKey("CreationRedemption"))
            {
                rtn.CreationFlag = tryParseInt32(keyValue["CreationRedemption"]);
            }
            if (keyValue.ContainsKey("Redemption"))
            {
                rtn.RedemptionFlag = tryParseInt32(keyValue["Redemption"]);
            }
            else if (keyValue.ContainsKey("CreationRedemption"))
            {
                rtn.RedemptionFlag = tryParseInt32(keyValue["CreationRedemption"]);
            }
            if (keyValue.ContainsKey("Recordnum"))
            {
                rtn.ComponentStockQty = tryParseInt32(keyValue["Recordnum"]);
            }
            else if (keyValue.ContainsKey("RecordNum"))
            {
                rtn.ComponentStockQty = tryParseInt32(keyValue["RecordNum"]);
            }
            if (keyValue.ContainsKey("PreTradingDay"))
            {
                rtn.PrevTradeDate = tryParseInt64(keyValue["PreTradingDay"]);
            }
            if (keyValue.ContainsKey("TradingDay"))
            {
                rtn.TradeDate = tryParseInt64(keyValue["TradingDay"]);
            }
            if (keyValue.ContainsKey("CashComponent"))
            {
                rtn.ETFSettlementCashAmt = tryParseDouble(keyValue["CashComponent"]);
            }
            if (keyValue.ContainsKey("NAVperCU"))
            {
                rtn.NAVperCU = tryParseDouble(keyValue["NAVperCU"]);
            }
            if (keyValue.ContainsKey("NAV"))
            {
                rtn.NAV = tryParseDouble(keyValue["NAV"]);
            }


            Match detailItemsMatch = Regex.Match(etfListFileContent, @"TAGTAG([\s\S]*?)ENDENDEND");
            if (detailItemsMatch.Success)
            {
                string detailItemsStr = detailItemsMatch.Groups[1].Value;
                var items = parseDetailItems(detailItemsStr, exch);
                rtn.ComponentDetailsGroup = new GWMKTETFListANS.ComponentDetails();
                rtn.ComponentDetailsGroup.Items.AddRange(items);
            }
            rtn.LocalExchStkCount = rtn.ComponentStockQty;
            rtn.StkID = rtn.FundID;
            rtn.ETFType = "0";//此处有疑问
            if (rtn.ComponentDetailsGroup != null && rtn.ComponentDetailsGroup.Items.Any())
                rtn.TotalAmount = rtn.ComponentDetailsGroup.Items.Sum(item => item.ETFApplyCashReplaceAmt);
            return rtn;
        }

        protected virtual List<GWMKTETFListANS.ComponentDetails.ComponentDetailsItem> parseDetailItems(string detailItemsStr, StockExchange exch)
        {
            List<GWMKTETFListANS.ComponentDetails.ComponentDetailsItem> items = new List<GWMKTETFListANS.ComponentDetails.ComponentDetailsItem>();
            using (StringReader reader = new StringReader(detailItemsStr))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] fields = line.Split('|');
                    if (fields.Length >= 6)
                    {
                        GWMKTETFListANS.ComponentDetails.ComponentDetailsItem detailItem = new GWMKTETFListANS.ComponentDetails.ComponentDetailsItem()
                        {
                            StkID = fields[0],
                            StkName = fields[1],
                            ExecuteQty = tryParseInt32(fields[2]),
                            ReplaceFlag = tryReadChar(fields[3]),
                            PremiumRate = tryParseDouble(fields[4]),
                            ETFRedemptionCashReplaceAmt = tryParseDouble(fields[5]),
                            StkTradeFlag = '0',
                            StkExchID = (char)exch
                        };
                        detailItem.ETFApplyCashReplaceAmt = detailItem.ETFRedemptionCashReplaceAmt;
                        items.Add(detailItem);
                    }
                }
            }
            return items;
        }

        //private string tryGetValueFromDic(Dictionary<string, string> dic,string key)
        //{
        //    if (dic.ContainsKey(key))
        //        return dic[key];
        //    else
        //        return null;
        //}
        protected int tryParseInt32(string str)
        {
            int rtn;
            int.TryParse(str, out rtn);
            return rtn;
        }
        protected long tryParseInt64(string str)
        {
            long rtn;
            long.TryParse(str, out rtn);
            return rtn;
        }
        protected double tryParseDouble(string str)
        {
            double rtn;
            double.TryParse(str, out rtn);
            return rtn;
        }
        protected char tryReadChar(string str)
        {
            char rtn = default(char);
            if (!string.IsNullOrEmpty(str))
            {
                rtn = str.Trim().FirstOrDefault();
            }
            return rtn;
        }
    }
}
